<?php

namespace App\Admin\Actions\Grid;

use App\Http\Controllers\Api\NotifyController;
use App\Models\Shop\WxShopOrder;
use App\Wen\Utils\ShopUtils;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\BatchAction;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class ShopOrderSupplyAction extends BatchAction
{
    /**
     * @return string
     */
    protected $title = '批量补单';

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $ids = $this->getKey();
        $supply_ids = [];
        foreach ($ids as $id){
            // 处理重复通知
            if(WxShopOrder::where([
                ['id','=', $id],
                ['pay_status', '=', 2]
            ])->exists()){
                continue;
            }
            $WxShopOrder = WxShopOrder::where('id', $id)->first();
            if($WxShopOrder){
                //SHOP
                WxShopOrder::where('id', $WxShopOrder->id)
                    ->update(['pay_status' => 2, 'status' => 1]);

                ShopUtils::paied_content_process($WxShopOrder->id);
                ShopUtils::split_shop_order_by_seller($WxShopOrder->id);
                ShopUtils::split_shop_order_by_type($WxShopOrder->id);
                ShopUtils::order_buys_and_stock($WxShopOrder->id);

            }else{
                continue;
            }
            $supply_ids[] = $id;
        }

        return $this->response()
            ->success('如下订单补单成功'.json_encode($supply_ids))
            ->refresh();
    }

    /**
     * @return string|array|void
     */
    public function confirm()
    {
        return ['确认补单?'];
    }

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [];
    }
}
